package com.example.servlet.user;

import com.alibaba.fastjson.JSON;
import com.example.model.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * 更新用户信息
 */
@WebServlet("/user/update")
@MultipartConfig
public class UpdateServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json;charset=utf-8");
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String fileName = savePhoto(req);
        String headPortrait = "img/"+fileName;
        //根据用户名更新用户表中的昵称和头像的路径
        User user = new User(username, nickname, fileName);
        UserService userService = new UserServiceImpl();
        userService.updateByUsername(user);
        resp.getWriter().println(JSON.toJSONString(ResponseData.ok(headPortrait)));
    }

    //保存头像
    private String savePhoto(HttpServletRequest req) throws IOException {
        Part part = null;
        InputStream inputStream = null;
        OutputStream os = null;
        String fileName = UUID.randomUUID().toString()+".jpg";
        try {
            part = req.getPart("photo");
            //将客户端上传的头像图片进行保存
            inputStream = part.getInputStream();
            byte[] bs = new byte[1024];
            int i = -1;
            //获取存放图片的路径
            String outPath = req.getServletContext().getRealPath("/img");
            os = new FileOutputStream(outPath+"\\"+fileName);
            while((i=inputStream.read(bs))!=-1){
                os.write(bs,0,i);
            }
        } catch (ServletException e) {
            e.printStackTrace();
        }finally {
            if(os != null){
                os.flush();
                os.close();
            }
            if(inputStream != null){
                inputStream.close();
            }
        }
        return fileName;
    }
}
